/**
 * 标签栏目
 */
import * as types from "../type";
import localStroage from "store";
const state = {
  // 存放所有浏览过的且不重复的路由数据
  visitedTag: localStroage.get("visitedTag") || [],
  //存放左侧被激活的菜单
  tagIndex: localStroage.get("tagIndex"),

  activeMenuName: localStroage.get("activeMenuname") || "",
  refresh: false
};

const getters = {
  getTag: state => state.visitedTag,
  getActiveMenuName: state => state.activeMenuName,
  getRefresh: state => state.refresh
  //activeMenuName: state => state.activeMenuName
};

const mutations = {
  [types.ADD_TAG](state, response) {
    const routeInfo = { ...response };
    // 打开新页签--添加路由数据的方法
    if (
      state.visitedTag.some(item => item.path === routeInfo.path) ||
      routeInfo.name === "index"
    ) {
      return;
    }
    state.visitedTag.push({
      name: routeInfo.name,
      path: routeInfo.path,
      title: routeInfo.meta.title || "no-title",
      query: routeInfo.query,
      params: routeInfo.params
    });
    localStroage.set("visitedTag", state.visitedTag);
  },
  [types.DEL_TAG](state, path) {
    let tagIndex = state.visitedTag.findIndex(item => item.path === path);
    state.tagIndex = tagIndex;
    state.visitedTag.splice(tagIndex, 1);
    localStroage.set("tagIndex", tagIndex);
    localStroage.set("visitedTag", state.visitedTag);
  },
  [types.SET_ACTIVE_MENU_NAME](state, name) {
    state.activeMenuName = name;
    localStroage.set("activeMenuName", name);
  },
  [types.SET_REFRESH_STATUS](state, status) {
    state.refresh = status;
  },
  [types.CLEAR_TAGS]() {
    localStroage.clearAll();
  }
};

const actions = {
  addTag: ({ commit }, data) => {
    commit(types.ADD_TAG, data);
  },
  delTag: ({ commit }, path) => {
    return new Promise(resolve => {
      // resolve方法：未来成功后回掉的方法
      console.log(state.tagIndex);
      commit(types.DEL_TAG, path);
      resolve(state);
    });
  },
  setActiveMenuName: ({ commit }, name) => {
    commit(types.SET_ACTIVE_MENU_NAME, name);
  },
  setRefreshStatus: ({ commit }, status) => {
    commit(types.SET_REFRESH_STATUS, status);
  },
  clearTags: ({ commit }) => {
    commit(types.CLEAR_TAGS);
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
